﻿using System.Web;
using System.Reflection;
using Kwan.Helper.Bitmaps;

namespace BG.Service
{
    public class BitmapHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string msg = "\"error\":{0},\"url\":\"{1}\"";
            try
            {
                string methodName = context.Request["a"];
                string fileName = string.Empty;
                BitmapHandler ops = new BitmapHandler();
                MethodInfo method = typeof(BitmapHandler).GetMethod(methodName);
                if (context.Request.Files.Count > 0)
                {
                    fileName = 
                        method.Invoke(ops, new object[] { context.Request["fileName"], context.Request.Files }).ToString();
                }
                msg = "{" + string.Format(msg, 0, fileName) + "}";
            }
            catch
            {
                msg = "{" + string.Format(msg, 1, "") + "}";
            }
            context.Response.Write(msg);
        }       
       
        public bool IsReusable
        {
            get { return false; }
        }

        public string Products(string fileName, HttpFileCollection files)
        {
            string FileName = string.Empty;
            using (Cutter imgCutter = new Cutter())
            {
                imgCutter.DefPath = "Upload\\Product";
                imgCutter.WidthArray = new int[] { 40, 340, 380, 800 };
                imgCutter.HeightArray = new int[] { 30, 255, 285, 600 };
                imgCutter.PathArray = new string[] { "p40", "p340", "p380", "p800" };
                for (int i = 0; i < files.Count; ++i)
                {
                    FileName = imgCutter.UploadImage(files[i].InputStream, string.Empty);
                }
            }
            return FileName;
        }

        public string News(string fileName, HttpFileCollection files)
        {
            string FileName = string.Empty;
            using (Cutter imgCutter = new Cutter())
            {
                imgCutter.DefPath = "Upload\\News";
                imgCutter.PathArray = new string[] { "pNews" };
                imgCutter.WidthArray = new int[] { 950 };
                imgCutter.HeightArray = new int[] { 713 };
                for (int i = 0; i < files.Count; ++i)
                {
                    FileName = imgCutter.UploadImage(files[i].InputStream, string.Empty);
                }
            }
            return "/Upload/News/pNews/" + FileName;
        }
    }
}
